const express = require("express");
const router = express.Router();
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const timezone = require("dayjs/plugin/timezone");

dayjs.extend(utc);
dayjs.extend(timezone);

const OpenAI = require("openai");

const openai = new OpenAI({
  baseURL: "https://ark.cn-beijing.volces.com/api/v3",
  apiKey: "cbe21b3d-b848-4c61-ba9e-8136fd17f88f",
});

const openaiR1 = new OpenAI({
  baseURL: "https://ark.cn-beijing.volces.com/api/v3",
  apiKey: "eb42333e-46ed-4455-8a04-6e8c2ea0f718",
});

let connectDAO = require("./connect.js");

// 登陆
router.get("/login", function (req, res) {
  const { PhoneNumber, Password } = req.query;
  const sql = `SELECT * FROM Officers WHERE PhoneNumber = '${PhoneNumber}' AND Password = '${Password}';`;
  connectDAO.queryDataBySQL(sql, (records) => {
    if (records.length > 0) {
      res.send({
        code: 200,
        msg: "Success",
        data: records[0],
      });
    } else {
      res.send({
        code: 201,
        msg: "账号或密码不正确",
      });
    }
  });
});

// 注册
router.post("/register", function (req, res) {
  const { Name, Department, PhoneNumber } = req.body;
  const sql = `INSERT INTO Officers (Name, Gender,Rank,Department,PhoneNumber, Permission,Password,HireDate) VALUES 
  ('${Name}', 'Male', '警员', '${
    Department || "派出所"
  }', '${PhoneNumber}', 'user','${PhoneNumber.slice(-6)}', '${dayjs().format(
    "YYYY-MM-DD"
  )}')`;
  connectDAO
    .queryDataBySQL(sql)
    .then(() => {
      res.send({ code: 200, msg: "Success" });
    })
    .catch((err) => {
      res.send({ code: 201, msg: "error", err });
    });
});

// 提交健康评估报表
router.post("/submit_health_report", function (req, res) {
  const {
    UserInfo: { Sex, Age, Name, OfficerID },
    AnswerList,
    InputAnswer,
  } = req.body;
  const sql = `INSERT INTO Evaluation (Name, Sex, Age, OfficerID, AnswerList, InputAnswer,CreateTime) VALUES 
  ('${Name}', '${Sex}', '${Age}', '${OfficerID}', '${AnswerList}','${InputAnswer}', '${dayjs().format(
    "YYYY-MM-DD HH:mm:ss"
  )}')`;
  connectDAO
    .queryDataBySQL(sql)
    .then((result) => {
      const EvaluationID = result.insertId;
      res.send({ code: 200, msg: "Success", EvaluationID });
    })
    .catch((err) => {
      res.send({ code: 201, msg: "error", err });
    });
});

// 根据健康评估表生成建议
router.get("/health_suggestion", async function (req, res) {
  const { EvaluationID, Content, mode } = req.query;
  const question = `1. 您的整体健康状况如何？（A.非常好 B.良好 C.一般 D.较差）  2. 您平均每天睡眠时间？（A.<5h B.5-6h C.7-8h D.>8h）  3. 您的饮食习惯？（A.高油高糖 B.偏素低脂 C.均衡 D.不规律）  4. 每周锻炼频率？（A.每天 B.3-5次 C.1-2次 D.很少）  5. 您有慢性病吗？（A.是 B.否）  6. 您的压力情况？（A.极大 B.较大 C.适中 D.很小）  7. 您的饮酒情况？（A.经常 B.偶尔 C.很少 D.从不）  8. 您的吸烟情况？（A.每天 B.偶尔 C.已戒 D.从不）  9. 您定期体检吗？（A.每年 B.两年 C.不定期 D.从不）  10. 您的心理状态？（A.常焦虑 B.偶尔低落 C.良好 D.乐观）  11. 您的健康管理习惯？（多选：A.锻炼 B.健康饮食 C.规律作息 D.体检）  12. 目前有哪些健康问题？（多选：A.高血压 B.糖尿病 C.心脏病 D.胃病）  13. 您如何缓解压力？（多选：A.运动 B.旅行 C.阅读音乐 D.冥想）  14. 其他健康状况补充：______  `;
  let content = "";
  let OfficerID = "";
  if (EvaluationID) {
    const result = await connectDAO.queryDataBySQL(
      `SELECT * FROM Evaluation WHERE EvaluationID = ${EvaluationID} ORDER BY CreateTime DESC;`
    );
    OfficerID = result[0].OfficerID;
    // if (result.length > 0) {
    content = `题目是${question}。选择题答案是${result[0].AnswerList}，中括号括着的是多选题答案,最后一题填空题答案是${result[0].InputAnswer}。请你根据题目和答案分点生成健康建议`;
    // }
  } else {
    if (!Content) {
      res.send({ code: 201, msg: "Content不能为空！" });
      return;
    }
  }
  let thisOpenAi = "";
  let model = "";
  if (EvaluationID || mode === "other") {
    thisOpenAi = openai;
    model = "doubao-1-5-lite-32k-250115";
  } else {
    thisOpenAi = openaiR2;
    model = "ep-20250306154002-7vlt7";
  }
  const completion = await thisOpenAi.chat.completions.create({
    messages: [
      { role: "system", content: "你是人工智能助手" },
      {
        role: "user",
        content: EvaluationID ? content : Content,
      },
    ],
    model,
  });
  let RecommendationID = "";
  if (EvaluationID) {
    // 入库
    const sql = `INSERT INTO Recommendation (EvaluationID, OfficerID, RecommendationText, CreateTime) 
    VALUES (${EvaluationID}, ${OfficerID}, '${
      completion.choices[0].message.content
    }', '${dayjs().format("YYYY-MM-DD HH:mm:ss")}')`;
    const { insertId } = await connectDAO.queryDataBySQL(sql);
    RecommendationID = insertId;
  }
  res.send({
    code: 200,
    msg: "Success",
    data: completion.choices[0].message.content,
    RecommendationID,
  });
});

// 获取某次评估的所有建议
router.get("/health_suggestion_by_EvaluationID", function (req, res) {
  const { EvaluationID } = req.query;
  connectDAO.queryDataBySQL(
    `SELECT * FROM Recommendation WHERE EvaluationID = '${EvaluationID}'`,
    (records) => {
      if (records.length > 0) {
        res.send({
          code: 200,
          msg: "Success",
          records,
          total: records.length,
        });
      } else {
        res.send({
          code: 200,
          msg: "no data",
          records,
        });
      }
    }
  );
});

// 获取用户的所有建议
router.get("/get_user_suggestions", function (req, res) {
  const { OfficerID } = req.query;
  connectDAO.queryDataBySQL(
    `SELECT * FROM Recommendation WHERE OfficerID = '${OfficerID}' ORDER BY createTime DESC`,
    (records) => {
      if (records.length > 0) {
        res.send({
          code: 200,
          msg: "Success",
          records,
          total: records.length,
        });
      } else {
        res.send({
          code: 200,
          msg: "no data",
          records,
        });
      }
    }
  );
});

// 获取用户所有评估记录
router.get("/get_user_evaluation_records", function (req, res) {
  const { OfficerID } = req.query;
  const sql = `SELECT * FROM Evaluation  ${
    OfficerID ? ` WHERE OfficerID = '${OfficerID}'` : ""
  }`;
  connectDAO.queryDataBySQL(sql, (records) => {
    if (records.length > 0) {
      res.send({
        code: 200,
        msg: "Success",
        records,
        total: records.length,
      });
    } else {
      res.send({
        code: 200,
        msg: "no data",
        records,
      });
    }
  });
});

//公开分享，于社区
router.put("/sharing_in_community", (req, res) => {
  const { RecommendationID, CommunityTitle } = req.body;
  const sql = `UPDATE Recommendation SET IsCommunity = 1,CommunityTitle = '${CommunityTitle}' WHERE RecommendationID = '${RecommendationID}'`;
  connectDAO.queryDataBySQL(sql).then(() => {
    res.send({ code: 200, msg: "Success" });
  });
});

// 获取社区记录
router.get("/community_records", function (req, res) {
  const sql = `SELECT * FROM Recommendation WHERE IsCommunity = 1`;
  connectDAO.queryDataBySQL(sql, (records) => {
    if (records.length > 0) {
      res.send({
        code: 200,
        msg: "Success",
        records,
        total: records.length,
      });
    } else {
      res.send({
        code: 200,
        msg: "no data",
        records: [],
      });
    }
  });
});

// 获取评论
router.get("/community_comments", function (req, res) {
  const { RecommendationID } = req.query;
  const sql = `SELECT c.*, o.Name AS OfficeName FROM Comment c LEFT JOIN 
      Officers o ON c.OfficerID = o.OfficerID WHERE RecommendationId = '${RecommendationID}' ORDER BY CreateTime DESC`;
  connectDAO.queryDataBySQL(sql, (records) => {
    if (records.length > 0) {
      res.send({
        code: 200,
        msg: "Success",
        records,
        total: records.length,
      });
    } else {
      res.send({
        code: 200,
        msg: "no data",
        records: [],
      });
    }
  });
});

// 发布评论
router.post("/publish_comment", function (req, res) {
  const { RecommendationID, OfficerID, Content } = req.body;
  const sql = `INSERT INTO Comment (RecommendationID, OfficerID, Content) VALUES 
  ('${RecommendationID}', '${OfficerID}', '${Content}')`;
  connectDAO
    .queryDataBySQL(sql)
    .then(() => {
      res.send({ code: 200, msg: "Success" });
    })
    .catch((err) => {
      res.send({ code: 201, msg: "error", err });
    });
});

// 获取officers
router.get("/get_officers_records", function (req, res) {
  const { OfficerID } = req.query;
  const sql = `SELECT * FROM Officers ${
    OfficerID ? "WHERE OfficerID = " + OfficerID : ""
  }`;
  connectDAO
    .queryDataBySQL(sql, (records) => {
      if (records.length > 0) {
        res.send({
          code: 200,
          msg: "Success",
          records,
          total: records.length,
        });
      } else {
        res.send({
          code: 200,
          msg: "no data",
          records,
        });
      }
    })
    .catch((err) => {
      res.send({ code: 201, msg: "error", err });
    });
});

module.exports = router;
